package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmMaterialDTO;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author zx
 * @date 2021/11/21 9:29
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Value("${file.oss.prefix}")
    String prefix;

    @Value("${file.oss.web-site}")
    String webSite;


    /**
     * 上传图片接口
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        //1 参数验证
        if (multipartFile==null || multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的文件");
        }

        //2 检验当前是否有用户
        WmUser wmUser= WmThreadLocalUtils.getUser();
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }

        //3 检验图片格式
        String originalFilename = multipartFile.getOriginalFilename();
        if (!checkFileSuffix(originalFilename)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }

        //4 上传到oss
        String fileId = null;
        try {
            //随机生成文件名
            String filename = UUID.randomUUID().toString().replace("-", "");
            //文件后缀
            String suffix=originalFilename.substring(originalFilename.lastIndexOf("."));

            fileId=fileStorageService.store(prefix,filename+suffix,multipartFile.getInputStream());
            System.out.println("文件名:"+filename+suffix);
            log.info("阿里云OSS 文件 fileId: {}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"服务器繁忙请稍后重试");
        }

        //5 保存到素材库
        WmMaterial wmMaterial=new WmMaterial();
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(wmUser.getId());
        save(wmMaterial);
        //6.页面显示
        wmMaterial.setUrl(webSite+fileId);

        //返回结果
        System.out.println("上传成功");
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材列表查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult List(WmMaterialDTO dto) {
        //1 参数检验
        WmUser wmUser=WmThreadLocalUtils.getUser();
        if (wmUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        dto.checkParam();

        //2.1查询
        Page<WmMaterial> pp=new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper= Wrappers.<WmMaterial>lambdaQuery();

        //2.2收藏
        if (dto.getIsCollection()!=null && dto.getIsCollection().intValue()==1){
            wrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }

        //2.3用户id
        wrapper.eq(WmMaterial::getUserId,wmUser.getId());

        //2.4 排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);

        //3.返回结果
        IPage<WmMaterial> rp=page(pp,wrapper);
        List<WmMaterial> records = rp.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (WmMaterial record : records) {
                record.setUrl(webSite + record.getUrl());
            }
        }

        System.out.println(records);
        //结果集封装
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),rp.getTotal(),records);
        System.out.println("素材列表加载成功");
        return responseResult;
    }


    /**
     * 删除图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPicture(Integer id) {

        //1 参数验证
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2 业务处理
        // 判断当前id是否被引用，如果被使用则禁止删除
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if(count > 0){
            ResponseResult.errorResult( AppHttpCodeEnum.DATA_NOT_ALLOW);
        }

        // 3.1删除素材库
        removeById(id);

        // 3.2删除图片OSS
        fileStorageService.delete(wmMaterial.getUrl());

        // 4 封装结果
        System.out.println("删除成功");
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 收藏与取消收藏
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数
        if(id == null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.更新状态
        WmMaterial material = getById(id);
        if (material == null) {
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"素材信息不存在");
        }
        //3 获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        if(!material.getUserId().equals(uid)){
            ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW,"只允许收藏自己上传的素材");
        }

        //4 返回结果
        material.setIsCollection(type);
        updateById(material);
        System.out.println("修改成功");
        return ResponseResult.okResult();
    }

    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path) {

        if (StringUtils.isBlank(path)){
            return false;
        }

        List<String> asList = Arrays.asList("jpg", "jpeg", "png", "gif");

        boolean isAllow = false;

        for (String suffix : asList) {
            if(path.endsWith(suffix)){
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }
}
